<?php
namespace app\models;
use ac\component\tool\Tool;

use Yii;

class Admin extends Basic
{
    public $oldpassword;
    public $passwordConfirm;
    
    
    public static function tableName()
    {
        return '{{%admin}}';
    }

    public function rules()
    {
        return [
            ['username', 'required', 'message' => 'username不能为空', 'on' => ['login', 'add']],
            ['username', 'string', 'message' => 'username必须是字符串',
                         'min' => 3, 'tooShort' => 'username最短3位',
                         'max' => 16, 'tooLong' => 'username最长16位', 'on' => ['login', 'add']],
            ['username', 'validateUsernameRepeat', 'on' => 'add'],
            ['password', 'required', 'message' => 'password不能为空', 'on' => ['login', 'add', 'modPassword', 'init']],
            ['password', 'string', 'message' => 'password必须是字符串', 'on' => ['login', 'add']],
            ['oldpassword', 'required', 'message' => '旧密码不能为空', 'on' => ['modPassword']],
            ['passwordConfirm', 'required', 'message' => '确认密码不能为空', 'on' => ['add', 'modPassword', 'init']],
            ['passwordConfirm', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码不一致', 'on' => ['add', 'modPassword', 'init']],
            ['password', 'validatePass', 'on' => 'login'],
            // ['role_id', 'default', 'value' => 0],
            ['role_id', 'integer', 'message' => 'role_id必须为数字，或数字字符串', 
                        'min'=>0, 'tooSmall' => 'role_id最小存储0', 
                        'max'=>4294967295, 'tooBig' => 'role_id最大存储4294967295'],
            // ['avatar', 'default', 'value' => ''],
            ['avatar', 'string', 'message' => 'avatar必须是字符串', 
                               'max' => 64, 'tooLong' => 'avatar最长64位'],
            // ['allowlogindate', 'default', 'value' => ''],
            ['allowlogindate', 'string', 'message' => 'allowlogindate必须是字符串', 
                               'max' => 16, 'tooLong' => 'allowlogindate最长16位'],
            ['lastloginip', 'string', 'message' => 'lastloginip必须是字符串', 
                            'max' => 64, 'tooLong' => 'lastloginip最长64位'], 
            ['lastlogin_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['lastlogin_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'lastlogin_time非yyyy-MM-dd HH:mm:ss格式'],
            // ['issuper', 'default', 'value' => 2],
            ['issuper', 'integer', 'message' => 'issuper必须为数字，或数字字符串'],
            ['issuper', 'in', 'range' => array(1, 2), 'message' => 'issuper值必须在1,2中选择'],
            ['creater', 'default', 'value' => 'system', 'on' => 'add'],
            ['creater', 'string', 'message' => 'creater必须是字符串', 
                         'max' => 16, 'tooLong' => 'creater最长16位'],
            // ['state', 'default', 'value' => 2],
            ['state', 'integer', 'message' => 'state必须为数字，或数字字符串'],
            ['state', 'in', 'range' => array(1, 2), 'message' => 'state值必须在1,2中选择'],
            // ['logintimes', 'default', 'value' => 0],
            ['logintimes', 'integer', 'message' => 'logintimes必须为数字，或数字字符串', 
                           'min'=>0, 'tooSmall' => 'logintimes最小存储0', 
                           'max'=>4294967295, 'tooBig' => 'logintimes最大存储4294967295'],
            ['sort', 'integer', 'message' => 'sort必须为数字，或数字字符串', 
                     'min'=>0, 'tooSmall' => 'sort最小存储0', 
                     'max'=>4294967295, 'tooBig' => 'sort最大存储4294967295'],
            ['add_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['add_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'add_time非yyyy-MM-dd HH:mm:ss格式'],
        ];
    }

    /*rules 验证登录信息是否吻合*/
    /*rules 验证用户名是否存在*/
    public function validateUsernameRepeat()
    {
        if(!$this->hasErrors()){
            $data = self::find()
                    ->where('username = :uname', [':uname' => $this->username])
                    ->one();
            if(!is_null($data)){
                $this->addError('repeatUsername', '该用户名已经存在');
            }
        }
    }

    /*rules 验证登录信息是否存在*/
    public function validatePass()
    {
        if(!$this->hasErrors()){
            $data = self::find()
            ->where('username = :uname and password = :pass', [':uname' => $this->username, ':pass' => md5(md5($this->password))])->one();
            // P(explode(',', $data->allowlogindate));
            // P($data);
            if(is_null($data)){
                $this->addError('password', '用户名或密码错误');
            }else if($data->state == 1){
                $this->addError('accountDisable', '该账户未启用');
            }else if( $data->issuper != 1 ){
                $week = date("w");
                if($week == 0){
                    $week = 7;
                }
                if(!in_array($week, explode(',', $data->allowlogindate))){
                    $this->addError('weekDisable', '周'. $week .'不允许登录');
                }
            }
        }
    }

    /*验证登录*/
    public function login($data)
    {
        // P($data);
        $this->scenario = 'login';
        if($this->load($data) and $this->validate()){//验证成功
            /*更新最后登录时间 和 登录次数*/
            $this->updateAll(['lastloginip' => Yii::$app->request->userIP, 'lastlogin_time' => date('Y-m-d H:i:s', time())], 'username = :uname', [':uname' => $this->username]);
            $this->updateAllCounters(['logintimes' => 1], 'username = :uname', [':uname' => $this->username]);
            /*取出登录了信息*/
            $info = $this::find()
                        ->select(['admin_id', 'username', 'role_id', 'avatar', 'issuper', 'add_time'])
                        ->where('username = :uname and password = :pass', [':uname' => $this->username, ':pass' => md5(md5($this->password))])->asArray()->one();
            // P($info);

            /*取出权限*/
            $adminRolePriv = AdminRolePriv::find()
                             ->select(['mid', 'apikeyname', 'm', 'c', 'a'])
                             ->where('role_id = :id', [':id' => $info['role_id']])
                             ->asArray()->all();

            /*增加白名单路由 主要是为了返回菜单中有白名单路由，方便前端判断*/
            // P(Yii::$app->params['allowRouter']);
            /*注释原因：放到前端判断 路由放到前端
            if(count(Yii::$app->params['allowRouter'])){
                foreach(Yii::$app->params['allowRouter'] as $k => $v){
                    $tmpArr = explode('=', $v);
                    $router = array(
                        'appid' => '',
                        'mid' => Yii::$app->params['allowRouterID'][$k],
                        'apikeyname' => '',
                        'm' => $tmpArr[0],
                        'c' => $tmpArr[1],
                        'a' => $tmpArr[2],
                    );
                    array_push($adminRolePriv, $router);
                }
            }
            */
            // P($adminRolePriv);

            /*登录信息存入缓存*/
            $loginInfo = array(
                'userInfo' => $info,
                'permissions' => $adminRolePriv,
            );
            Yii::$app->session->set('loginInfo', (object)$loginInfo);
            return true;
        }
        return false;
    }

    /*添加管理员*/
    public function addAdmin($data)
    {
        $this->scenario = 'add';
        if(empty($data['Admin']['role_id'])){
            $data['Admin']['role_id'] = 0;
        }
        $data['Admin']['creater'] = $this->userInfo['username'];
        if(isset($data['Admin']['state'])){
            $data['Admin']['state'] = Tool::changeBool($data['Admin']['state']);
        }
        $data['Admin']['add_time'] = date('Y-m-d H:i:s', time());
        // P($data);
        if($this->load($data) and $this->validate()){
            $this->password = md5(md5($this->password));
            if($this->save(false)){
                $admin_id = $this->getPrimaryKey();
                $this->updateAll(['sort' => $admin_id], 'admin_id = :id', [':id' => $admin_id]);
                return true;
            }
        }
        return false;
    }

    /*
    修改管理员
    $data   修改的数据
    $id     主键
    */
    public function modifyAdmin($data, $id)
    {
        $admin = Admin::find()->where('admin_id = :id', [':id' => $id])->one();

        if(isset($data['Admin']['oldpassword'])){//只修改密码
            $this->scenario = 'modPassword';
            if($admin->password != md5(md5($data['Admin']['oldpassword']))){
                $this->addError('oldpassword', '旧密码错误');
                return false;
            }
        }
        if(isset($data['Admin']['state'])){
            $data['Admin']['state'] = Tool::changeBool($data['Admin']['state']);
        }
        // P($data);
        if(!is_null($admin)){
            if($this->load($data) and $this->validate()){
                if(isset($this->password)){
                    $this->password = md5(md5($this->password));
                    $admin->password = $this->password;
                }
                if(isset($this->role_id)){
                    $admin->role_id = $this->role_id;
                }
                if(isset($this->avatar)){
                    $admin->avatar = $this->avatar;
                }
                if(isset($this->allowlogindate)){
                    $admin->allowlogindate = $this->allowlogindate;
                }
                if(isset($this->state)){
                    $admin->state = $this->state;
                }
                if($admin->save(false)){
                    return true;
                }
            }
        };
        return false;
    }

    /*初始化企业超级管理员密码 只会有一个*/
    public function initPwd($data)
    {
        $this->scenario = 'init';
        $admin = Admin::find()->where('issuper = 1')->one();
        if(!is_null($admin)){
            if($this->load($data) and $this->validate()){
                if(isset($this->password)){
                    $this->password = md5(md5($this->password));
                    $admin->password = $this->password;
                }
                if($admin->save(false)){
                    return true;
                }
            }
        };
        return false;

    }


    /*
    排序 按照sort倒叙排列
    $sort
    */
    public function setSort($sort)
    {
        $origin = $sort;
        $sort = implode(',', $sort);
        $sql = 'select sort from {{%admin}} where find_in_set (admin_id, :sort) order by sort desc, add_time desc limit 0, 1';
        //获取 传过来的数据中，在老排序的第一位数据 是当前数据中排序值最大的，
        //当前面没有数据的时候，此最大排序值就是起始值
        $currMaxSort = Admin::findBySql($sql, [':sort' => $sort])->one();
        $sql = 'select sort from {{%admin}} where sort > (' . $sql . ') order by sort asc, add_time asc limit 0, 1';
        // echo $sql;
        $admin = Admin::findBySql($sql, [':sort' => $sort])->one();//获取老排序 紧挨着的前一个排序值
        if(is_null($admin) or $admin->sort == 0){//如果没有 或前一个排序值也0，则从1开始计算
            $sortNum = $currMaxSort->sort+1;
        }else{
            $sortNum = $admin->sort;
        }
        // P($sortNum);
        $transaction = Yii::$app->db->beginTransaction();//事物处理
        try{
            foreach($origin as $k => $v){
                $sortNum--;
                $this->updateAll(['sort' => $sortNum], 'admin_id = :id', [':id' => $v]);
            }
            $transaction->commit();
            return true;
        }catch(\Exception $exception){
            $transaction->rollback();
        };
        return false;
    }

    /*关联查询 角色信息*/
    public function getAdminRole()
    {
        $adminRole = $this->hasOne(AdminRole::className(), ['role_id' => 'role_id'])
                    ->select(['role_id', 'rolename']);
        return $adminRole;
    }

}